package com.zys.el.time.service.impl;

import com.zys.el.time.constants.RedisConstants;
import com.zys.el.time.entity.User;
import com.zys.el.time.fegin.UserClient;
import com.zys.el.time.service.redis.CacheClient;
import com.zys.el.time.vojo.UserVo;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
public class UserService {
    @Resource
    private UserClient userClient;
    @Resource
    private CacheClient cacheClient;

    private UserVo getOneById(Long userId){
        Map<Long, User> userMap = userClient.getUserListByBatchId(Collections.singletonList(userId));
        return new UserVo(userMap.get(userId));
    }

    public UserVo queryUser(Long userId){
        String userKey = RedisConstants.USER_KEY + userId;
        return cacheClient.queryWithoutLock(userKey, userId, UserVo.class,
                this::getOneById, RedisConstants.USER_TTL, RedisConstants.NULL_TTL, TimeUnit.SECONDS);
    }

    public Map<Long, UserVo> queryUserMap(List<Long> ids){
        Map<Long, User> userMap = userClient.getUserListByBatchId(ids);
        HashMap<Long, UserVo> res = new HashMap<>();
        userMap.forEach((k, v)-> res.put(k, new UserVo(v)));
        return res;
    }
}
